// pages/subscribe/subscribe.js
let app = getApp()
let request = require('../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    pageAllHeight: app.globalData.pageAllHeight,
    screenHeight: 0,
    parkId: 0,
    parkInfo: {},
    subscribeRule: [],
    timeTab: [],
    timeTabIndex: 0,
    timeTabArrObject: [],
    // timeListArr: ['7:00-7:30', '7:30-8:00', '8:00-8:30', '8:30-9:00', '9:00-9:30', '9:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00', '12:00-12:30', '12:30-13:00', '13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00', '15:00-15:30', '15:30-16:00', '16:00-16:30', '16:30-17:00'],
    timeListArr: ['7:00-8:00', '8:00-9:00', '9:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00'],
    timeList: [],
    timeListIndex: -1,
    carNumList: [],
    carNumberIndex: 0,
    payMoney: 0,
    haveApplyList: [],
    longitude: 0,
    latitude: 0,
    searchDialog: false,
    searchResult: [],
    searcheVip: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let homeSbuBtn = options.homeSbuBtn ? JSON.parse(options.homeSbuBtn) : false
    console.log(homeSbuBtn);
    this.setData({
      parkId: options.parkId,
      homeSbuBtn: homeSbuBtn,
      parkInfo: {
        parkName: options.parkName,
        reserveParkSpace: options.reserveParkSpace
      },
      screenHeight: wx.getSystemInfoSync().screenHeight
    })
    if (homeSbuBtn == true) {
      this.getUserLocation()
    } else {
      this.getSubscribeRule()
      this.getHaveApply()
    }
    this.setTimeBar()
    this.getCarNumList()
    this.setTimeList()
  },
  /**
 * 获取用户当前位置
 */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({ longitude, latitude });
        //  附近有月租规则停车场
        that.getRecentlySubscribe()
      }
    })
  },
  /**
   * 附近有月租规则停车场
   */
  getRecentlySubscribe() {
    let that = this
    let parmas = {
      latitude: this.data.latitude,
      longitude: this.data.longitude
    }
    request.http('/park/info/getNearbyReserveParkList', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            parkId: data.data.id,
            'parkInfo.parkName': data.data.parkName
          })
          that.getSubscribeRule()
          that.getHaveApply()
        }
      })
  },
  /**
   * 打开搜索弹窗
   */
  showSearchDialog() {
    this.setData({
      searchDialog: true,
      searcheVip: wx.getStorageSync('lmtc_searcheSubscribe')
    })
  },
  /**
  * 关闭搜索弹窗
  */
  hiddenSearchDialog() {
    this.setData({
      searchDialog: false
    })
  },
  /**
   * 获取搜索框内容
   */
  getSearch(e) {
    let that = this
    let val = e.detail.value
    this.setData({
      searchAddress: val
    })
    let parmas = {
      keyword: val
    }
    request.http('/park/info/getParkByName', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            searchResult: data.data
          })
        }
      })
  },
  /**
   * 点击搜索到的停车场事件
   */
  selectPark(e) {
    let index = e.currentTarget.dataset.index
    let searchResult = this.data.searchResult
    let record = {
      parkName: searchResult[index].parkName,
      address: searchResult[index].parkAddress,
      id: searchResult[index].id
    }
    this.setData({
      parkId: searchResult[index].id,
      'parkInfo.parkName': searchResult[index].parkName,
      searchDialog: false
    })
    let searcheSubscribe = wx.getStorageSync('lmtc_searcheSubscribe');
    if (Array.isArray(searcheSubscribe)) {
      if (searcheSubscribe.length == 2) {
        searcheSubscribe.splice(1, 1);
        searcheSubscribe.unshift(record);
      } else {
        searcheSubscribe.unshift(record);
      }
    } else {
      searcheSubscribe = [];
      searcheSubscribe.push(record);
    }
    wx.setStorageSync('lmtc_searcheSubscribe', searcheSubscribe);
    this.getSubscribeRule()
    this.getHaveApply()
  },
  /**
   * 点击历史搜索记录
   */
  selectSearchPark(e) {
    let searcheVip = this.data.searcheVip
    let index = e.currentTarget.dataset.index
    console.log('搜索停车场：', searcheVip)
    this.setData({
      parkId: searcheVip[index].id,
      'parkInfo.parkName': searcheVip[index].parkName,
      searchDialog: false
    })
    this.getSubscribeRule()
    this.getHaveApply()
  },
  /**
   * 获取停车场预约剩余车位
   */
  getParkingApplyNumber(index) {
    let that = this
    let timeTabArrObject = that.data.timeTabArrObject
    let date = new Date()
    let year = date.getFullYear()
    index = index ? index : this.data.timeTabIndex
    let startTime = this.data.timeTab[index]
    startTime = startTime.split('.')
    let parmas = {
      parkId: this.data.parkId,
      reserveDate: year + '-' + startTime[0] + '-' + startTime[1]
    }
    request.http('/park/info/getParkReservesSpace', 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          if (data.data == 0) {
            for (var i = 0; i < timeTabArrObject.length; i++) {
              if (timeTabArrObject[i].date == parmas.reserveDate) {
                timeTabArrObject[i].forbidden = true
              }
            }
          }
          that.setData({
            'parkInfo.reserveParkSpace': data.data,
            timeTabArrObject
          })
        }
      })
  },
  /**
   * 获取停车场预约收费规则
   */
  getSubscribeRule() {
    let that = this
    request.http('/promotion/reserve-fee-scale/getMonthRulePaytypeByParkId', 'GET', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let subscribeRule = data.data
          for (var i = 0; i < subscribeRule.length; i++) {
            var reserveBeginTime = subscribeRule[i].reserveBeginTime
            var reserveEndTime = subscribeRule[i].reserveEndTime
            subscribeRule[i].reserveBeginTime = reserveBeginTime.substring(0, 5)
            subscribeRule[i].reserveEndTime = reserveEndTime.substring(0, 5)
          }
          that.setData({
            subscribeRule
          })
        }
      })
  },
  // 已预约车辆
  getHaveApply() {
    let that = this
    request.http('/order-reserve/park-reserve-record/get-unfinished-by-parkid', 'GET', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            haveApplyList: data.data
          })
        }
      })
  },
  /**
   * 设置时间切换栏
   */
  setTimeBar() {
    let date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let timeTab = this.data.timeTab
    let timeTabArrObject = this.data.timeTabArrObject
    timeTabArrObject.push({ date: year + '-' + month + '-' + day, forbidden: false })
    timeTab.push(month + '.' + day)
    for (var i = 0; i < 1; i++) {
      day += 1
      if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        if (day > 31) {
          month += 1
          day = 1
        }
      } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        if (day > 30) {
          month += 1
          day = 1
        }
      } else if (month == 2) {
        if (year % 4 == 0) {
          if (day > 29) {
            month += 1
            day = 1
          }
        } else {
          if (day > 28) {
            month += 1
            day = 1
          }
        }
      }
      if (month > 12) {
        month = 1
      }
      timeTab.push(month + '.' + day);
      timeTabArrObject.push({ date: year + '-' + month + '-' + day, forbidden: false })
    }
    this.setData({
      timeTab,
      timeTabArrObject
    })
    // for (var i = 0; i < timeTab.length; i++) {
    //   this.getParkingApplyNumber(i)
    // }
  },
  /**
   * 设置时间列表
   */
  setTimeList() {
    let date = new Date()
    let hour = date.getHours() + ''
    hour = hour.length < 2 ? '0' + hour : hour
    let month = date.getMinutes() + ''
    month = month.length < 2 ? '0' + month : month
    let timeList = this.data.timeListArr
    let newTimeList = []
    for (var i = 0; i < timeList.length; i++) {
      var time = timeList[i].split('-')
      time[0] = time[0].length < 5 ? '0' + time[0] : time[0]
      if ((time[0] < hour + ':' + month) && this.data.timeTabIndex == 0) {
        newTimeList.push({ forbidden: true, time: timeList[i] })
      } else {
        newTimeList.push({ forbidden: false, time: timeList[i] })
      }
    }
    this.setData({
      timeList: newTimeList
    })
  },
  /**
   * 选择tab
   */
  selectBar(e) {
    let index = e.target.dataset.index
    if (this.data.timeTabIndex == index) {
      return
    }
    this.setData({
      timeTabIndex: index,
      timeListIndex: -1,
      payMoney: 0
    })
    this.setTimeList()
    this.getParkingApplyNumber()
  },
  /**
   * 选择时间
   */
  selectTime(e) {
    let date = new Date()
    let hour = date.getHours() + ''
    hour = hour.length < 2 ? '0' + hour : hour
    let month = date.getMinutes() + ''
    month = month.length < 2 ? '0' + month : month
    let index = e.target.dataset.index
    let timeList = this.data.timeListArr
    var time = timeList[index].split('-')
    if (this.data.timeListIndex == index) {
      return
    }
    time[0] = time[0].length < 5 ? '0' + time[0] : time[0]
    if (time[0] < '11:00') {
      this.setData({
        payMoney: this.data.subscribeRule[0].amount
      })
    } else {
      this.setData({
        payMoney: this.data.subscribeRule[1].amount
      })
    }
    this.setData({
      timeListIndex: index
    })
  },
  /**
  * 查询车牌列表
  */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i]['select'] = true
              } else {
                list[i]['select'] = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },
  /**
   * 选择车牌号
   */
  selectCar(e) {
    let index = e.currentTarget.dataset.index
    let carList = this.data.carNumList
    for (var i = 0; i < carList.length; i++) {
      carList[i]['select'] = false
    }
    carList[index]['select'] = true
    this.setData({
      carNumList: carList,
      carNumberIndex: index
    })
  },
  // 支付预约
  toPay() {
    let date = new Date()
    let year = date.getFullYear()
    let dateTime = year + '-' + this.data.timeTab[this.data.timeTabIndex].split('.')[0] + '-' + this.data.timeTab[this.data.timeTabIndex].split('.')[1]
    let carNumber = this.data.carNumList[this.data.carNumberIndex].carNumber
    if (!carNumber) {
      wx.showToast({
        title: '未选择入场车牌',
        icon: 'none'
      })
      return
    }
    let parkId = this.data.parkId
    let startTime = this.data.timeListArr[this.data.timeListIndex]
    let endTime = this.data.timeListArr[this.data.timeListIndex]
    if (!startTime) {
      wx.showToast({
        title: '未选择预约时间',
        icon: 'none'
      })
      return
    }
    startTime = startTime.split('-')[0]
    endTime = endTime.split('-')[1]
    let price = this.data.payMoney
    // let price = 0.01
    startTime = dateTime + ' ' + startTime + ':00'
    endTime = dateTime + ' ' + endTime + ':00'
    let parmas = {
      carNumber: carNumber,
      parkId: parkId,
      reserveAmount: price,
      reserveBeginTime: startTime,
      reserveEndTime: endTime
    }
    let haveApplyList = this.data.haveApplyList
    for (var i = 0; i < haveApplyList.length; i++) {
      if (haveApplyList[i].carNumber == carNumber && haveApplyList[i].reserveBeginTime.split(' ')[0] == startTime.split(' ')[0]) {
        wx.showToast({
          title: '您在当前车场已存在' + carNumber + '的预约如仍需预约请继续操作',
          icon: 'none',
        })
        return
      }
    }
    request.http('/order-reserve/park-reserve-record/reserve', 'POST', parmas, 0)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          wx.requestPayment({
            timeStamp: data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: data.data.signType, // 签名算法，非必填，（预先约定或者后台传回）
            paySign: data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) { // 成功后的回调函数
              wx.showToast({
                title: '预约申请已提交',
                icon: 'none',
                success() {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/applayRecord/applayRecord',
                    })
                  }, 500)
                }
              })
            },
            fail(res) {
              // Toast.fail('支付失败');
              console.log(res)
            }
          })
        }
      })
  }
})